package com.pine.manager.pineframework.trigger.impl;

import cn.hutool.core.collection.CollUtil;
import com.pine.common.beans.enums.DeletedEnum;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysUserAssignRoleRequest;
import com.pine.common.trigger.TriggerContext;
import com.pine.dao.pineframework.entity.SysRoleUser;
import com.pine.dao.pineframework.entity.SysUser;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.bo.SysUserBo;
import com.pine.manager.pineframework.trigger.AbstractTriggerTemplateAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统用户分配角色 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-16
 */
@Component
@Slf4j
public class SysUserAssignRoleTrigger extends AbstractTriggerTemplateAdapter<SysUserAssignRoleRequest, Boolean> {

    public SysUserAssignRoleTrigger() {
        super(TriggerTypeEnum.SYS_USER_ASSIGN_ROLE);
    }

    @Override
    protected void before(TriggerContext<SysUserAssignRoleRequest> triggerContext) {
        SysUserAssignRoleRequest request = triggerContext.getTriggerRequest();
        SysUserBo oldSysUserBo = sysUserManager.getOneByUniqueKey(request.getUserId(), SysUser::getId);
        if (Objects.isNull(oldSysUserBo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_NOT_EXIST);
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    public Boolean trigger(TriggerContext<SysUserAssignRoleRequest> triggerContext) {
        SysUserAssignRoleRequest request = triggerContext.getTriggerRequest();
        // 删除用户角色关联关系
        sysRoleUserManager.deleteByUserId(request.getUserId());

        List<Long> roleIds = request.getRoleIds();
        if (CollUtil.isNotEmpty(roleIds)) {
            List<SysRoleUser> roleUsers = roleIds.stream().map(roleId -> {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setUserId(request.getUserId());
                sysRoleUser.setRoleId(roleId);
                sysRoleUser.setDeleted(DeletedEnum.NOT_DELETED.getCode());
                sysRoleUser.setCreateTime(LocalDateTime.now());
                return sysRoleUser;
            }).toList();

            sysRoleUserManager.saveBatch(roleUsers);
        }
        return true;
    }
}
